<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="700px">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import { ColEx } from "/@/components/Form/src/types"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./data"
  import * as extIdpApi from "/@/api/iam/extIdp"
  import { useMessage } from "/@/hooks/web/useMessage"

  // 自适应列配置
  const wrapperCol: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 24, // ≥992px
    xl: 24, // ≥1200px
    xxl: 24, // ≥1600px
  }

  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])

  const isUpdate = ref(true)
  const selectdUser = ref<any>({})

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {

      try {
        await resetFields()
        setDrawerProps({ confirmLoading: false, loading: true })
        isUpdate.value = !!data?.isUpdate
        if (unref(isUpdate)) {
          data.record = await extIdpApi.getIdpTmpl({ id: data.record.id })
          await setFieldsValue({
            ...data.record,
          })
        }
      } finally {
        setDrawerProps({ loading: false })
      }

  })

  const title = computed(() => (!unref(isUpdate) ? "新增身份源模板" : "编辑身份源模板"))
  async function handleSubmit(v) {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      await extIdpApi.saveOrUpdateIdpTmpl({ ...values, userId: selectdUser.value.id }, isUpdate.value)
      closeDrawer()
      emit("success")
      createMessage.success(`${title.value}成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
